var Detail = function () {
    this.title = ko.observable('');
    this.context = ko.observable('');
    this.updateTime = ko.observable('');
};
var Search = function () {
    this.isLoading = ko.observable(false);
    this.searchType = ko.observable('1');
    this.searchKey = ko.observable('');
    this.articleItems = ko.observableArray();
    this.currentPage = ko.observable(1);
    this.total = ko.observable(0);
    this.pageSize = 20;
    this.detail = ko.observable(new Detail());
    this.showPager = ko.computed(function() {
        return this.total() > 0;
    }, this);
    var self = this;

    this.placeholder = ko.computed(function() {
        var txt = "";
        if(self.searchType().length > 0) {
            if (self.searchType() === '1') {
                txt = "按关键字搜索";
            } else if (self.searchType() === '2') {
                txt = "按文章标题搜索";
            } else if(self.searchType() === '3') {
                txt = "按内容搜索";
            }
        }
        return txt;
    }, this);

    this.search = function () {
        self.fetchArticle(parseInt(this.searchType()), this.searchKey(), 1, self.pageSize, null);
    }

    this.gotoPage = function (pageIndex) {
        if(self.total() === 0) {
            return;
        }
        var pageCount = Math.ceil(self.total() / self.pageSize);
        if(pageIndex > pageCount) {
            pageIndex = pageCount;
        }
        self.fetchArticle(parseInt(self.searchType()), self.searchKey(), pageIndex, self.pageSize, null);
    }

    this.fetchArticle = function(type, key, pageIndex, pageSize, callback) {
        self.searchKey(key);

        if(!pageIndex || pageIndex <= 0) {
            pageIndex = 1;
        }

        if(self.isLoading()) {
            return;
        }
        $.ajax({
            type: 'POST',
            url: '/article/search',
            contentType: 'application/json',
            data: ko.toJSON({
                type: type,
                key: key,
                current: pageIndex,
                size: pageSize
            }),
            beforeSend: function (xhr) {
                self.isLoading(true);
                $('.items').toggleClass('loading');
            },
            success: function (res) {
                self.articleItems.removeAll();
                if(res.code === "200") {
                    self.total(res.data.total);
                    self.currentPage(res.data.current);
                    var results = res.data.results;
                    $.each(results, function (index, item) {
                        self.articleItems.push(item);
                    });

                    self.setArticlePager(res.data.current, self.pageSize, res.data.total);

                    if(callback) {
                        callback(res.data.results);
                    }
                }
            },
            complete: function (xhr, ts) {
                self.isLoading(false);
                $('.items').toggleClass('loading');
            }
        });
    }

    this.fetchDetail = function (item) {
        $.ajax({
            type: 'POST',
            url: '/article/detail?id=' + item.id,
            beforeSend: function (xhr) {

            },
            success: function (res) {
                if(res.code === "200") {
                    self.detail(res.data);
                    $(".article-overflow").animate({scrollTop: 0}, 300);
                }
            },
            complete: function (xhr, ts) {

            }
        })
    }

    this.clearKey = function () {
        self.searchKey('');
    }

    this.initView = function () {
        self.fetchArticle(-1, null, 1, self.pageSize, function (data) {
            // 初始化页面，默认显示第一篇文章
            if(Array.isArray(data) && data.length > 0) {
                self.fetchDetail(data[0]);
            }
        });
    }
    
    this.setArticlePager = function (page, recPerPage, recTotal) {
        $('#article-pager').pager({
            page: page,
            recPerPage: recPerPage,
            recTotal: recTotal,
            onPageChange: function(state, oldState) {
                if (state.page !== oldState.page) {
                    // console.log('页码从', oldState.page, '变更为', state.page);
                    self.gotoPage(state.page);
                }
            }
        });
    }
};

var searchVm = new Search();
ko.applyBindings(searchVm);
searchVm.initView();

$("#inputSearch").keydown(function(event){
    if(event.keyCode === 13){
        searchVm.search();
    }
});